package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.search.pojo.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.common.ApThreadLocalUtil;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
@Transactional
public class ApUserSearchServiceImpl   implements ApUserSearchService {
@Autowired
    MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索历史记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        //查询当前用户关键字
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch search = mongoTemplate.findOne(query, ApUserSearch.class);
        //存在更新到最新时间
        if (search != null) {
            search.setCreatedTime(new Date());
            mongoTemplate.save(search);
            return;
        }
        //查询当前用户下的搜索记录数量不超过10,封装数据
        Query query1 = Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query1, ApUserSearch.class);
        ApUserSearch apUserSearch = new ApUserSearch();
        apUserSearch.setKeyword(keyword);
        apUserSearch.setUserId(userId);
        apUserSearch.setCreatedTime(new Date());
        if (apUserSearches.size() <10 ||apUserSearches==null ) {
            mongoTemplate.save(apUserSearch);
        }else {
            //超过10条,替换最后一天数据
            ApUserSearch apUserSearch1 = apUserSearches.get(apUserSearches.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(apUserSearch1.getId())),apUserSearch);
        }

    }

    /**
     * 查询搜索历史
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        Integer useId = ApThreadLocalUtil.getUser().getId();
        if (useId != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Query query = Query.query(Criteria.where("userId").is(useId)).with(Sort.by(Sort.Direction.DESC));
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }

    /**
     * 根据id删除历史记录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult deleteById(HistorySearchDto dto) {
        Integer useId = ApThreadLocalUtil.getUser().getId();
if (useId != null) {
    return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
}

        DeleteResult remove = mongoTemplate.remove(Query.query(Criteria.where("userId").is(useId).and("id").is(dto.getId())), ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }
}